import {computed, delay, designPage, reactive, useRefs} from "@peryl/react-compose";
import {$ai, $dialog, $message, $notice, Button, Checkbox, DatePicker, Form, FormItem, i18n, iAnotherRule, Icon, Input, InputGroup, InputNumber, PageCard, PageCardContent, PageCardTitle, Radio, RadioGroup, Segment, SegmentGroup, Select, SelectOption, Tooltip, VirtualList} from "plain-design";
import '../demo-form/virtual-form-multiple-page.locale';

export default designPage(() => {

  type iFieldRender = (data: { field: string, formData: any }) => any

  interface iFieldMeta {
    type: 'input' | 'select' | 'date' | 'number' | 'textarea' | 'radio',
    label: string,
    field: string,
    required?: boolean,
    rule?: Omit<iAnotherRule, 'label' | 'field'>,
    render?: iFieldRender,
  }

  const { refs, onRef } = useRefs({ form: Form });

  const _fields = ((): iFieldMeta[] => {
    return [
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.OrderID').d('订单编号'), field: 'OrderID' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.CustomerID').d('客户编号'), field: 'CustomerID' },
      {
        type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.CustomerName').d('客户姓名'), field: 'CustomerName', required: false,
        render: ({ field, formData }) => {
          return state.useTextInput ? (
            <span>{formData[field]}</span>
          ) : (
            <InputGroup>
              <Input v-model={formData[field]} v-slots={{
                suffix: () => (
                  <Tooltip message={i18n.$intl('page.virtualFormMultiplePage.customerNameTips').d("不为空则客户电话、客户邮箱必填")}>
                    <span><Icon icon="pi-info-circle-fill"/></span>
                  </Tooltip>
                )
              }}/>
              <Button label={i18n.$intl('page.virtualFormMultiplePage.customRenderField').d("自定义渲染字段")}/>
            </InputGroup>
          );
        },
      },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.CustomerPhone').d('客户电话'), field: 'CustomerPhone' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.CustomerEmail').d('客户邮箱'), field: 'CustomerEmail' },
      { type: 'date', label: i18n.$intl('page.virtualFormMultiplePage.fields.OrderTime').d('下单时间'), field: 'OrderTime' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.OrderStatus').d('订单状态'), field: 'OrderStatus' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.OrderAmount').d('订单金额'), field: 'OrderAmount' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.PaymentMethod').d('支付方式'), field: 'PaymentMethod' },
      { type: 'radio', label: i18n.$intl('page.virtualFormMultiplePage.fields.PaymentStatus').d('支付完成'), field: 'PaymentStatus' },
      { type: 'date', label: i18n.$intl('page.virtualFormMultiplePage.fields.PaymentTime').d('支付时间'), field: 'PaymentTime' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ReceiverName').d('收货人姓名'), field: 'ReceiverName' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ReceiverPhone').d('收货人电话'), field: 'ReceiverPhone' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ShippingAddress').d('收货地址'), field: 'ShippingAddress' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.PostalCode').d('邮编'), field: 'PostalCode' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ShippingMethod').d('配送方式'), field: 'ShippingMethod' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ShippingStatus').d('配送状态'), field: 'ShippingStatus' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.CourierID').d('配送员编号'), field: 'CourierID' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.CourierName').d('配送员姓名'), field: 'CourierName' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.InvoiceType').d('发票类型'), field: 'InvoiceType' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.InvoiceTitle').d('发票抬头'), field: 'InvoiceTitle' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.InvoiceNumber').d('发票号码'), field: 'InvoiceNumber' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.TotalItems').d('商品总数'), field: 'TotalItems' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.DiscountAmount').d('优惠金额'), field: 'DiscountAmount' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ShippingFee').d('运费金额'), field: 'ShippingFee' },
      { type: 'textarea', label: i18n.$intl('page.virtualFormMultiplePage.fields.OrderNote').d('订单备注'), field: 'OrderNote' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.RelatedOrderID').d('关联订单编号'), field: 'RelatedOrderID' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.OrderSource').d('订单来源'), field: 'OrderSource' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.OrderType').d('订单类型'), field: 'OrderType' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.CustomerServiceNote').d('客服备注'), field: 'CustomerServiceNote' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductList').d('商品列表'), field: 'ProductList' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductID1').d('商品编号1'), field: 'ProductID1' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductName1').d('商品名称1'), field: 'ProductName1' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductQuantity1').d('商品数量1'), field: 'ProductQuantity1' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductPrice1').d('商品单价1'), field: 'ProductPrice1' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductID2').d('商品编号2'), field: 'ProductID2' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductName2').d('商品名称2'), field: 'ProductName2' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductQuantity2').d('商品数量2'), field: 'ProductQuantity2' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductPrice2').d('商品单价2'), field: 'ProductPrice2' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ReturnQuantity2').d('退货数量2'), field: 'ReturnQuantity2' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ReturnAmount').d('退货金额'), field: 'ReturnAmount' },
      { type: 'textarea', label: i18n.$intl('page.virtualFormMultiplePage.fields.ReturnReason2').d('退货原因2'), field: 'ReturnReason2' },
      { type: 'radio', label: i18n.$intl('page.virtualFormMultiplePage.fields.RefundStatus').d('已退款'), field: 'RefundStatus' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.RefundAmount').d('退款金额'), field: 'RefundAmount' },
      { type: 'date', label: i18n.$intl('page.virtualFormMultiplePage.fields.RefundTime').d('退款时间'), field: 'RefundTime' },
      { type: 'date', label: i18n.$intl('page.virtualFormMultiplePage.fields.OrderConfirmationTime').d('订单确认时间'), field: 'OrderConfirmationTime' },
      { type: 'date', label: i18n.$intl('page.virtualFormMultiplePage.fields.OrderCancellationTime').d('订单取消时间'), field: 'OrderCancellationTime' },
      { type: 'textarea', label: i18n.$intl('page.virtualFormMultiplePage.fields.OrderCancellationReason').d('订单取消原因'), field: 'OrderCancellationReason', rule: { type: 'string', max: 5, min: 2 } },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.MemberLevel').d('会员级别'), field: 'MemberLevel' },
      { type: 'radio', label: i18n.$intl('page.virtualFormMultiplePage.fields.PointsChange').d('积分变动'), field: 'PointsChange' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ActivityID').d('活动编号'), field: 'ActivityID' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ActivityName').d('活动名称'), field: 'ActivityName' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ActivityType').d('活动类型'), field: 'ActivityType' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ActivityDescription').d('活动描述'), field: 'ActivityDescription' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ActivityStatus').d('活动状态'), field: 'ActivityStatus' },
      { type: 'date', label: i18n.$intl('page.virtualFormMultiplePage.fields.CreateTime').d('创建时间'), field: 'CreateTime' },
      { type: 'date', label: i18n.$intl('page.virtualFormMultiplePage.fields.UpdateTime').d('更新时间'), field: 'UpdateTime' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ActivityGoal').d('活动目标'), field: 'ActivityGoal' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ExpectedParticipants').d('预期参与人数'), field: 'ExpectedParticipants' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ExpectedSalesAmount').d('预期销售额'), field: 'ExpectedSalesAmount' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.Duration').d('活动时长'), field: 'Duration' },
      { type: 'radio', label: i18n.$intl('page.virtualFormMultiplePage.fields.OnlineOrOffline').d('线上'), field: 'OnlineOrOffline' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.Location').d('活动地点'), field: 'Location' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ParticipantID').d('参与者ID'), field: 'ParticipantID' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ParticipantName').d('参与者姓名'), field: 'ParticipantName' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ParticipantContact').d('参与者联系方式'), field: 'ParticipantContact' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ParticipantStatus').d('参与者状态'), field: 'ParticipantStatus' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.RewardType').d('奖励类型'), field: 'RewardType' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.RewardQuantity').d('奖励数量'), field: 'RewardQuantity' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.RewardValue').d('奖励价值'), field: 'RewardValue' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.RewardClaimCondition').d('奖励领取条件'), field: 'RewardClaimCondition' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.PromotionChannel').d('宣传渠道'), field: 'PromotionChannel' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.PromotionBudget').d('宣传预算'), field: 'PromotionBudget' },
      { type: 'textarea', label: i18n.$intl('page.virtualFormMultiplePage.fields.PromotionContent').d('宣传内容'), field: 'PromotionContent' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.MarketingStrategy').d('营销策略'), field: 'MarketingStrategy' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.TotalBudget').d('总预算'), field: 'TotalBudget' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.VenueCost').d('场地费用'), field: 'VenueCost' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.MaterialCost').d('物料费用'), field: 'MaterialCost' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.RewardCost').d('奖品费用'), field: 'RewardCost' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.PromotionCost').d('宣传费用'), field: 'PromotionCost' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.StaffCost').d('人员费用'), field: 'StaffCost' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ActualParticipants').d('参与人数'), field: 'ActualParticipants' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ActualSalesAmount').d('销售额'), field: 'ActualSalesAmount' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ConversionRate').d('转化率'), field: 'ConversionRate' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ReturnOnInvestment').d('ROI'), field: 'ReturnOnInvestment' },
      { type: 'textarea', label: i18n.$intl('page.virtualFormMultiplePage.fields.UserFeedback').d('用户反馈'), field: 'UserFeedback' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.SatisfactionScore').d('活动满意度'), field: 'SatisfactionScore' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ActivityManager').d('活动负责人'), field: 'ActivityManager' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ContactInfo').d('联系方式'), field: 'ContactInfo' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.EmergencyContact').d('紧急联系人'), field: 'EmergencyContact' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.PhotosOrVideos').d('活动照片或视频'), field: 'PhotosOrVideos' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.Partners').d('合作伙伴'), field: 'Partners' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.Highlights').d('活动亮点'), field: 'Highlights' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.RiskAssessment').d('风险评估'), field: 'RiskAssessment' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ImprovementMeasures').d('改进措施'), field: 'ImprovementMeasures' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.FollowUpPlan').d('后续计划'), field: 'FollowUpPlan' },
      { type: 'textarea', label: i18n.$intl('page.virtualFormMultiplePage.fields.Notes').d('备注'), field: 'Notes' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductID').d('商品ID'), field: 'ProductID' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductName').d('商品名称'), field: 'ProductName' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductDescription').d('商品描述'), field: 'ProductDescription' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductImageURL').d('商品图片URL'), field: 'ProductImageURL' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductCategory').d('商品分类'), field: 'ProductCategory' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductSubcategory').d('商品子分类'), field: 'ProductSubcategory' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.Brand').d('品牌'), field: 'Brand' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.Manufacturer').d('制造商'), field: 'Manufacturer' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.Barcode').d('商品条形码'), field: 'Barcode' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.UPCCode').d('商品UPC码'), field: 'UPCCode' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductSize').d('商品尺寸'), field: 'ProductSize' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductColor').d('商品颜色'), field: 'ProductColor' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductMaterial').d('商品材质'), field: 'ProductMaterial' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductWeight').d('商品重量'), field: 'ProductWeight' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductVolume').d('商品体积'), field: 'ProductVolume' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.TargetAudience').d('适用人群'), field: 'TargetAudience' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ApplicableScene').d('适用场景'), field: 'ApplicableScene' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ExpirationDate').d('保质期'), field: 'ExpirationDate' },
      { type: 'textarea', label: i18n.$intl('page.virtualFormMultiplePage.fields.Origin').d('产地'), field: 'Origin' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.PackagingType').d('包装类型'), field: 'PackagingType' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.MarketPrice').d('市场价'), field: 'MarketPrice' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.SalePrice').d('售价'), field: 'SalePrice' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.PromotionPrice').d('促销价'), field: 'PromotionPrice' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.CostPrice').d('成本价'), field: 'CostPrice' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.StockQuantity').d('库存数量'), field: 'StockQuantity' },
      { type: 'radio', label: i18n.$intl('page.virtualFormMultiplePage.fields.MinimumStockAlert').d('最低库存警告'), field: 'MinimumStockAlert' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.StockStatus').d('库存状态'), field: 'StockStatus' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.StockLocation').d('库存位置'), field: 'StockLocation' },
      { type: 'date', label: i18n.$intl('page.virtualFormMultiplePage.fields.StockUpdateTime').d('库存更新时间'), field: 'StockUpdateTime' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.SoldQuantity').d('已售数量'), field: 'SoldQuantity' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.TotalSalesAmount').d('总销售额'), field: 'TotalSalesAmount' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.AverageSalesAmount').d('平均销售额'), field: 'AverageSalesAmount' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.MaxSalesAmount').d('最高销售额'), field: 'MaxSalesAmount' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.MinSalesAmount').d('最低销售额'), field: 'MinSalesAmount' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.OrderQuantity').d('订单数量'), field: 'OrderQuantity' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ReturnQuantity').d('退货数量'), field: 'ReturnQuantity' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ReturnRate').d('退货率'), field: 'ReturnRate' },
      { type: 'textarea', label: i18n.$intl('page.virtualFormMultiplePage.fields.ReturnReason').d('退货原因'), field: 'ReturnReason' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ReviewQuantity').d('评价数量'), field: 'ReviewQuantity' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.AverageRating').d('平均评分'), field: 'AverageRating' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.MaxRating').d('最高评分'), field: 'MaxRating' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.MinRating').d('最低评分'), field: 'MinRating' },
      { type: 'textarea', label: i18n.$intl('page.virtualFormMultiplePage.fields.ReviewContent').d('评价内容'), field: 'ReviewContent' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ReviewerID').d('评价者ID'), field: 'ReviewerID' },
      { type: 'date', label: i18n.$intl('page.virtualFormMultiplePage.fields.ReviewTime').d('评价时间'), field: 'ReviewTime' },
      { type: 'textarea', label: i18n.$intl('page.virtualFormMultiplePage.fields.FeedbackContent').d('反馈内容'), field: 'FeedbackContent' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.FeedbackStatus').d('反馈状态'), field: 'FeedbackStatus' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.RelatedCoupons').d('关联优惠券'), field: 'RelatedCoupons' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.RelatedPromotions').d('关联促销活动'), field: 'RelatedPromotions' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.RelatedOrders').d('关联订单'), field: 'RelatedOrders' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.RelatedSuppliers').d('关联供应商'), field: 'RelatedSuppliers' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.RelatedRecommendations').d('关联商品推荐'), field: 'RelatedRecommendations' },
      { type: 'textarea', label: i18n.$intl('page.virtualFormMultiplePage.fields.ShippingOrigin').d('发货地'), field: 'ShippingOrigin' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ShippingCost').d('运费'), field: 'ShippingCost' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ShippingMethod2').d('配送方式2'), field: 'ShippingMethod2' },
      { type: 'date', label: i18n.$intl('page.virtualFormMultiplePage.fields.EstimatedShipTime').d('预计发货时间'), field: 'EstimatedShipTime' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ShippingStatus2').d('配送状态2'), field: 'ShippingStatus2' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.CourierCompany').d('物流公司'), field: 'CourierCompany' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.TrackingNumber').d('物流跟踪号'), field: 'TrackingNumber' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductStatus').d('商品状态'), field: 'ProductStatus' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductTags').d('商品标签'), field: 'ProductTags' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductKeywords').d('商品关键词'), field: 'ProductKeywords' },
      { type: 'radio', label: i18n.$intl('page.virtualFormMultiplePage.fields.RelatedArticlesOrTutorials').d('关联文章或教程'), field: 'RelatedArticlesOrTutorials' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.VideoTutorialURL').d('商品视频教程URL'), field: 'VideoTutorialURL' },
      { type: 'textarea', label: i18n.$intl('page.virtualFormMultiplePage.fields.UsageInstructions').d('商品使用说明'), field: 'UsageInstructions' },
      { type: 'textarea', label: i18n.$intl('page.virtualFormMultiplePage.fields.MaintenanceMethods').d('商品保养方法'), field: 'MaintenanceMethods' },
      { type: 'textarea', label: i18n.$intl('page.virtualFormMultiplePage.fields.SafetyWarnings').d('商品安全警告'), field: 'SafetyWarnings' },
      { type: 'textarea', label: i18n.$intl('page.virtualFormMultiplePage.fields.AfterSalesServicePolicy').d('售后服务政策'), field: 'AfterSalesServicePolicy' },
      { type: 'textarea', label: i18n.$intl('page.virtualFormMultiplePage.fields.ReturnPolicy').d('退换货政策'), field: 'ReturnPolicy' },
      { type: 'select', label: i18n.$intl('page.virtualFormMultiplePage.fields.ProductLifecycle').d('商品生命周期'), field: 'ProductLifecycle' },
      { type: 'radio', label: i18n.$intl('page.virtualFormMultiplePage.fields.RelatedAdvertisingActivities').d('关联广告活动'), field: 'RelatedAdvertisingActivities' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.SearchRanking').d('搜索排名'), field: 'SearchRanking' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ClickRate').d('点击率'), field: 'ClickRate' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.ConversionRate2').d('转化率2'), field: 'ConversionRate2' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.Exposure').d('曝光量'), field: 'Exposure' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.InventoryTurnoverRate').d('库存周转率'), field: 'InventoryTurnoverRate' },
      { type: 'date', label: i18n.$intl('page.virtualFormMultiplePage.fields.FirstListTime').d('首次上架时间'), field: 'FirstListTime' },
      { type: 'date', label: i18n.$intl('page.virtualFormMultiplePage.fields.LastUpdateTime').d('最后更新时间'), field: 'LastUpdateTime' },
      { type: 'number', label: i18n.$intl('page.virtualFormMultiplePage.fields.StockWarningThreshold').d('库存预警阈值'), field: 'StockWarningThreshold' },
      { type: 'input', label: i18n.$intl('page.virtualFormMultiplePage.fields.BatchNumber').d('商品批次号'), field: 'BatchNumber' },
    ];
  })();

  const state = reactive({
    useTextInput: false,
    /*列数*/
    columns: 3,
    /*编辑的表单数据对象*/
    formData: ((): any => {
      return _fields.reduce((prev, item, index) => {
        item.required == null && (item.required = true);
        prev[item.field] = (() => {
          switch (item.type) {
            case 'input':
            case 'textarea':
              return item.label;
            case 'date':
              return DatePicker.plainDate.today().getDayJs().format('YYYY-MM-DD');
            case 'number':
              return index;
            case 'select':
              return 'new';
            case 'radio':
              return 'Y';
          }
        })();
        return prev;
      }, {} as any);
    })(),
    /*所有的字段*/
    fields: _fields,
  });

  /*动态计算要渲染的字段，当客户姓名(CustomerName)有值的情况下，渲染字段【客户电话】以及【客户邮箱】，并且必填*/
  const fields = computed((): iFieldMeta[] => {
    if (!state.formData.CustomerName) {
      return state.fields.filter(i => i.field !== 'CustomerPhone' && i.field !== 'CustomerEmail');
    } else {
      return state.fields;
    }
  });

  const groupCache: Record<string, iFieldMeta[] | undefined> = {};

  const fieldGroups = computed((): iFieldMeta[][] => {

    const ret: iFieldMeta[][] = [];

    let last: iFieldMeta[] = [];
    ret.push(last);
    fields.value.forEach(field => {
      if (field.type === 'textarea') {
        if (last.length) {
          last = [];
          ret.push(last);
        }
        last.push(field);
        last = [];
        ret.push(last);
      } else {
        if (last.length >= state.columns) {
          last = [];
          ret.push(last);
        }
        last.push(field);
      }
    });

    /*对已经计算过的对象缓存，避免由于生成新的对象导致渲染新的虚拟行*/
    ret.forEach((group, groupIndex) => {
      const id = group.map(i => i.field).join('_');
      if (!!groupCache[id]) {
        ret[groupIndex] = groupCache[id]!;
      } else {
        groupCache[id] = group;
      }
    });

    return ret;
  });

  /*根据要渲染的字段计算iAnotherRule校验规则*/
  const rules = computed(() => {
    return fields.value.reduce((prev, item) => {
      if (item.required) {
        prev.push({
          field: item.field,
          required: true,
          label: item.label,
        });
      }
      !!item.rule && prev.push({
        ...item.rule,
        label: item.label,
        field: item.field,
      });
      return prev;
    }, [] as iAnotherRule[]);
  });

  const selectOptions: { label: string, val: string }[] = [
    { label: i18n.$intl('page.virtualFormMultiplePage.selectOptions.new').d("新建"), val: 'new' },
    { label: i18n.$intl('page.virtualFormMultiplePage.selectOptions.to_pay').d("待支付"), val: 'to_pay' },
    { label: i18n.$intl('page.virtualFormMultiplePage.selectOptions.to_ship').d("待发货"), val: 'to_ship' },
    { label: i18n.$intl('page.virtualFormMultiplePage.selectOptions.cancel').d("已取消"), val: 'cancel' },
  ];

  /*根据类型动态渲染编辑表单组件*/
  const renderHandler: Record<iFieldMeta['type'], iFieldRender> = {
    input: ({ field, formData }) => {
      return <Input v-model={formData[field]}/>;
    },
    select: ({ field, formData }) => {
      return <Select v-model={formData[field]}>{selectOptions.map(i => (<SelectOption label={i.label} key={i.val} val={i.val}/>))}</Select>;
    },
    number: ({ field, formData }) => {
      return <InputNumber v-model={formData[field]}/>;
    },
    date: ({ field, formData }) => {
      return <DatePicker v-model={formData[field]}/>;
    },
    textarea: ({ field, formData }) => {
      return <Input textarea v-model={formData[field]}/>;
    },
    radio: ({ field, formData }) => {
      return (
        <RadioGroup v-model={formData[field]} itemWidth={'50%'}>
          <Radio label={i18n.$it('base.yes').d("是")} val="Y"/>
          <Radio label={i18n.$it('base.no').d("否")} val="N"/>
        </RadioGroup>
      );
    },
  };

  /*校验以及保存*/
  const save = async () => {
    await refs.form?.validate();
    $message.success(i18n.$intl('page.virtualFormMultiplePage.validateSuccess').d('保存成功!'));
  };

  const verticalLabel = i18n.state.currentLang === 'en-us';

  /*文本生成表单数据对象*/
  const getUserContent = () => {
    const userContent = _fields.map(field => {
      let showValue = state.formData[field.field];
      if (field.type === 'select') {
        showValue = selectOptions.find(i => i.val == showValue)?.label;
      }
      if (field.type === 'radio') {
        showValue = showValue === 'Y' ? '是' : '否';
      }
      if (field.type === 'date') {
        showValue = DatePicker.plainDate(showValue, { displayFormat: 'YYYY年MM月DD日', valueFormat: 'YYYY-MM-DD' }).getDisplay();
      }
      return `${field.label}：${showValue}`;
    }).join('\n');
    console.log(userContent);
  };

  const clearFormData = async () => {
    state.formData = {};
    refs.form?.clearValidate();
  };

  const openAiChat = async () => {

    // console.log(getUserContent())
    // return

    const systemPrompt = `
       你是一名专业的自然语言分析师，需要你帮我将用户的输入转化为表单数据对象，目前支持的字段如下所示：
       ${_fields.map(field => `{label:"${field.label}", field:"${field.field}"}`).join('\n')}

       label是字段的显示名称，field是字段的标识，；比如用户提供的内容为“${_fields[0].label}: 用户提供的值”，
       那么你返回的表单数据对象就得用这个字段标识以及用户提供的值保存在表单数据对象中，比如“{${_fields[0].field}: "用户提供的值"}”
       最后如果这个字段的type（字段的数据类型）如果是“date”，那么需要你将日期字符串格式化为YYYY-MM-DD；
       如果这个字段的type为“radio”，那么这个字段的值应该格式化为N和Y；
       最后注意的是，你必须以如下格式返回数据，也就是“字段名:字段值”的格式，如下所示：

       OrderID:解析得到的OrderID
       CustomerID:解析得到的CustomerID
      `;

    // console.log(systemPrompt)

    const closeDialog = $dialog({
      title: "智能填写",
      editType: 'textarea',
      editRequired: true,
      confirmButton: true,
      cancelButton: true,
      disableCancelOnClickMask: true,
      handleConfirm: async data => {

        /*const chatResult = await $ai.chatSystem(
          data.editValue as any,
          systemPrompt,
        );
        try {
          const newFormData = JSON.parse(chatResult.message);
          state.formData = newFormData;
          console.log(newFormData);
          await delay(78);
          refs.form?.clearValidate();
        } catch (e: any) {
          const errorMessage = e.message || JSON.stringify(e);
          $notice.error(errorMessage);
        }*/

        let formProxyData: Record<string, any> | undefined = undefined;

        const handleFullText = (fullText: string) => {
          // console.log({ fullText });
          if (!formProxyData) {
            state.formData = {};
            formProxyData = state.formData;
            closeDialog();
          }
          /*只处理最后两行*/
          let list = fullText.split('\n').slice(-2);
          list.forEach(item => {
            const [key, val] = item.split(':');
            formProxyData![key] = val;
          });
        };

        await $ai.chatStream({
          messages: [
            { role: 'system', content: systemPrompt },
            { role: 'user', content: data.editValue as any }
          ],
          onReceiving: ({ fullText }) => {handleFullText(fullText);},
          onFinish: (fullText) => {console.log({ ...state.formData });},
        });
      }
    });
  };

  return () => (
    <PageCard full>
      <PageCardTitle title={i18n.$intl('page.virtualFormMultiplePage.pageTitle', { val: fields.value.length }).d(`虚拟多列表单(共${fields.value.length}个字段)`)}>
        <Checkbox label={i18n.$intl('page.virtualFormMultiplePage.pureText').d("纯文本")} v-model={state.useTextInput}/>
        <span>{i18n.$intl('page.virtualFormMultiplePage.columns').d("列数")}: </span>
        <SegmentGroup v-model={state.columns}>
          <Segment label={i18n.$intl('page.virtualFormMultiplePage.columnOptions.0').d("一列")} val={1}/>
          <Segment label={i18n.$intl('page.virtualFormMultiplePage.columnOptions.1').d("二列")} val={2}/>
          <Segment label={i18n.$intl('page.virtualFormMultiplePage.columnOptions.2').d("三列")} val={3}/>
        </SegmentGroup>
        <Button label="AI填写" asyncHandler={openAiChat}/>
        <Button label="清空表单" onClick={clearFormData}/>
        <Button label={i18n.$it('base.edit.save').d("保存")} mode="fill" onClick={save}/>
      </PageCardTitle>
      <PageCardContent full>
        <Form
          ref={onRef.form}
          full
          inputMode={state.useTextInput ? 'text' : undefined}
          verticalLabel={verticalLabel}
          labelWidth={verticalLabel ? 20 : 150}
          modelValue={state.formData}
          anotherRules={rules.value}
          validateMessagePosition="bottom-right">
          <VirtualList
            data={fieldGroups.value}
            size={40}
            dynamicSize
            v-slots={{
              default: ({ item, vid }) => {
                const fieldGroup = item as iFieldMeta[];
                return (
                  <div data-vid={vid} key={vid} style={{ display: 'inline-block', width: '100%' }}>
                    {fieldGroup.map((field) => (
                      <div style={{ width: field.type === 'textarea' ? '100%' : `calc(100% / ${state.columns})`, display: 'inline-block', paddingLeft: '12px', boxSizing: 'border-box' }} key={field.field}>
                        <FormItem
                          labelWidth={verticalLabel ? undefined : "200"}
                          field={field.field}
                          label={field.label + ` (${fields.value.findIndex(i => i.field == field.field) + 1})`}
                          required={field.required}
                        >
                          {field.render ?
                            field.render({ field: field.field, formData: state.formData })
                            : renderHandler[field.type]({ field: field.field, formData: state.formData })}
                        </FormItem>
                      </div>
                    ))}
                  </div>
                );
              }
            }}
          />
        </Form>
      </PageCardContent>
    </PageCard>
  );
});
